Kotlin

Collection Operations Overview

Swift

Common operations

                  val numbers = listOf("one", "two", "three", "four")  
numbers.filter { it.length > 3 }  // nothing happens with `numbers`, result is lost
println("numbers are still $numbers")
val longerThan3 = numbers.filter { it.length > 3 } // result is stored in `longerThan3`
println("numbers longer than 3 chars are $longerThan3")
                
                    let numbers = listOf("one", "two", "three", "four")  
numbers.filter { it.length > 3 }  // nothing happens with `numbers`, result is lost
print("numbers are still $numbers")
let longerThan3 = numbers.filter { it.length > 3 } // result is stored in `longerThan3`
print("numbers longer than 3 chars are $longerThan3")
                  
                  val numbers = listOf("one", "two", "three", "four")
val filterResults = mutableListOf<String>()  //destination object
numbers.filterTo(filterResults) { it.length > 3 }
numbers.filterIndexedTo(filterResults) { index, _ -> index == 0 }
println(filterResults) // contains results of both operations
                
                    let numbers = listOf("one", "two", "three", "four")
let filterResults = mutableListOf<String>()  //destination object
numbers.filterTo(filterResults) { it.length > 3 }
numbers.filterIndexedTo(filterResults) { index, _ -> index == 0 }
print(filterResults) // contains results of both operations
                  
                  // filter numbers right into a new hash set, 
// thus eliminating duplicates in the result
val result = numbers.mapTo(HashSet()) { it.length }
println("distinct item lengths are $result")
                
                    // filter numbers right into a new hash set, 
// thus eliminating duplicates in the result
let result = numbers.mapTo(HashSet()) { it.length }
print("distinct item lengths are $result")
                  

Write operations

                  val numbers = mutableListOf("one", "two", "three", "four")
val sortedNumbers = numbers.sorted()
println(numbers == sortedNumbers)  // false
numbers.sort()
println(numbers == sortedNumbers)  // true
                
                    let numbers = mutableListOf("one", "two", "three", "four")
let sortedNumbers = numbers.sorted()
print(numbers == sortedNumbers)  // false
numbers.sort()
print(numbers == sortedNumbers)  // true